<template>
  <ElButton  @click="fetchImage">{{ $t('common.downloadFile') }}</ElButton>
  <!-- 错误提示 -->
  <!-- <SvgIcon v-if="error" icon="icon-park-outline:error-picture" style="font-size: 30px;color: rgb(245, 34, 45);" />
    <img v-if="blobUrl" :src="blobUrl" :alt="altText" :style="imgStyle" :onerror="handleImageError" /> -->
</template>

<script setup lang="ts">
import { getToken, serveConfig } from "@/axios-utils";
import { localStg } from "@/utils/storage";
import SvgIcon from "@/components/custom/svg-icon.vue";
import { computed, defineComponent, onMounted, onUnmounted, ref, watch } from "vue";
import { GetFileUrl } from "./file-helper";
const props = defineProps({
  fId: {
    type: String,
    required: true
  },
  fileName: {
    type: String
  },
  errorText: {
    type: String,
    default: 'Error'
  }
});

const blobUrl = ref<string | null>();
const loading = ref(false)
const error = ref<string | null>();
const fetchImage = () => {
  loading.value = true;
  error.value = null;
  const url = GetFileUrl(props.fId);
  cleanupBlobUrl();
  fetch(url, {
    headers: {
      Authorization: `Bearer ${getToken()}`,
    },
  })
    .then(response => {
      // 处理 HTTP 错误状态
      if (!response.ok) {
        throw new Error('文件不存在或服务器错误');
      }

      // 从响应头解析文件名
      const contentDisposition = response.headers.get('content-disposition');
      let filename = 'download';
      if (props.fileName) {
        filename = props.fileName;
      } else if (contentDisposition) {
        // 优先解析 RFC 5987 编码的文件名 (filename*)
        const encodedFilenameMatch = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i);
        if (encodedFilenameMatch) {
          filename = decodeURIComponent(encodedFilenameMatch[1]);
        }
        // 如果不存在编码版本，尝试普通文件名
        else {
          const basicFilenameMatch = contentDisposition.match(/filename=["']?([^;"']+)["']?/i);
          if (basicFilenameMatch) filename = basicFilenameMatch[1];
        }
      }

      return Promise.all([response.blob(), filename]);
    })
    .then(([blob, filename]) => {
      // 创建临时下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = decodeURIComponent(filename); // 处理编码文件名
      document.body.appendChild(a);
      a.click();

      // 清理资源
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    })
    .catch(err => {
      console.error('下载失败:', err);
    })
    .finally(() => {
      loading.value = false;
    });

}

// 组件挂载时自动加载
onUnmounted(() => {
  cleanupBlobUrl()
})

const cleanupBlobUrl = () => {
  if (blobUrl.value) {
    URL.revokeObjectURL(blobUrl.value)
    blobUrl.value = null
  }
}

</script>

<style scoped></style>
